package com.ruoyi.client.vo;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * Jeepay业务对象基类
 */
public abstract class JeepayObject {

    /**
     * 将对象转换为Map
     * @return Map对象
     */
    public Map<String, Object> toMap() {
        Map<String, Object> map = new HashMap<>();
        Field[] fields = this.getClass().getDeclaredFields();

        try {
            for (Field field : fields) {
                field.setAccessible(true);
                JSONField jsonField = field.getAnnotation(JSONField.class);

                String key;
                if (jsonField != null && !"".equals(jsonField.name())) {
                    key = jsonField.name();
                } else {
                    key = field.getName();
                }

                Object value = field.get(this);
                if (value != null) {
                    map.put(key, value);
                }
            }
        } catch (Exception e) {
            // 忽略异常
        }

        return map;
    }

    /**
     * 将对象转换为JSONObject
     * @return JSONObject对象
     */
    public JSONObject toJSONObject() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.putAll(this.toMap());
        return jsonObject;
    }

    /**
     * 将对象转换为JSON字符串
     * @return JSON字符串
     */
    @Override
    public String toString() {
        return toJSONObject().toString();
    }
}
